<script setup lang="ts">
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import {addOrUpdateAttributeAPI,getAttributeDetailAPI,deleteAttributeAPI, getAttributeListAPI,getCategoryOneListAPI, getCategoryTwoListAPI, getCategoryThreeListAPI } from '@/api/product/attribute'
import type { CategoryOneItem, CategoryTwoItem, CategoryThreeItem, AttributeItem} from '@/types/product/attribute'
import { onMounted, ref} from 'vue'
// import type { CategoryOneItem, CategoryTwoItem, CategoryThreeItem, AttributeItem} from '@/types/attribute'
import { ElMessage, ElMessageBox } from 'element-plus';

// 选定分类参数
const categoryParmas = ref({
    category1Id: '',
    category2Id: '' ,
    category3Id: '',
})

// 一级分类数据
const categoryOneList = ref<CategoryOneItem[]>([])

// 获取一级分类数据
const getCategoryOne = async() => {
    const res = await getCategoryOneListAPI()
    console.log(res);
    categoryOneList.value = res.data
}

// 选中一级分类
const handleCategory1 = () => {
    getCategoryTwo(categoryParmas.value.category1Id)
    categoryParmas.value.category2Id = ''
    categoryParmas.value.category3Id = ''
    categoryTwoList.value = []
    categoryThreeList.value = []
}

// 二级分类数据
const categoryTwoList = ref<CategoryTwoItem[]>([])

// 获取二级分类数据
const getCategoryTwo = async (id: string) => {
    const res = await getCategoryTwoListAPI(parseInt(id))
    categoryTwoList.value = res.data
}

// 选中二级分类
const handleCategory2 = () => {
    getCategoryThree(categoryParmas.value.category2Id)
    categoryParmas.value.category3Id = ''
    categoryThreeList.value = []
}

// 三级分类数据
const categoryThreeList = ref<CategoryThreeItem[]>([])

// 获取三级分类数据
const getCategoryThree = async (id: string) => {
    const res = await getCategoryThreeListAPI(parseInt(id))
    // console.log(res);
    categoryThreeList.value = res.data
}

// 选中三级分类
const handleCategory3 = async() => {
    getAttributeList()
   
}

// 获取平台属性数据
const getAttributeList = async () => {
    tableLoading.value = true
    const res = await getAttributeListAPI(parseInt(categoryParmas.value.category1Id),parseInt(categoryParmas.value.category2Id),parseInt(categoryParmas.value.category3Id))
    console.log(res);
    attributeList.value = res.data.length > 20 ? res.data.slice(0,20) : res.data
    tableLoading.value = false
}

// 平台属性数据
const attributeList = ref<AttributeItem[]>([])

// 表格加载效果
const tableLoading = ref(false)

// 是否显示添加属性表单
const isShowAddAttribute = ref(false)

// 添加属性
const addAddAttribute =  async (row?: AttributeItem ) => {
    if(row?.id) {
        // 修改
        // 发送请求获取属性详情
        const res = await getAttributeDetailAPI(row.id)
        console.log(res);
        addAttributeForm.value.attrName = row.attrName
        addAttributeForm.value.attrValueList = res.data
        addAttributeForm.value.id = row.id
    } else {
        // 添加
    }
    isShowAddAttribute.value = true
}

// 删除属性
const deleteAttribute = (row: AttributeItem) => {
    ElMessageBox.confirm("温馨提示","您确定删除该属性吗?",{
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    }).then( async () => {
        const res = await deleteAttributeAPI(row.id as number | string)
        if(res.code === 200) {
            ElMessage.success("删除成功")
        } else {
            ElMessage.error("删除失败")
        }
        getAttributeList()
    }).catch(() => {

    })
}
// 添加属性表单数据
const addAttributeForm = ref<AttributeItem>({
    attrName: '',
    attrValueList: [],
    categoryId: 0,
    categoryLevel: 0
})

// 添加属性值按钮
const addAttributeValue = () => {
    addAttributeForm.value.attrValueList.push({
        valueName: '',
        flag: false
    })
}

// 保存属性
const saveAttribute = async() => {
    addAttributeForm.value.categoryId = parseInt(categoryParmas.value.category3Id)
    addAttributeForm.value.categoryLevel = 3
    const res = await addOrUpdateAttributeAPI(addAttributeForm.value)
    // console.log(res);
    if(res.code === 200) {
        if(addAttributeForm.value.id) {
            ElMessage.success("修改成功")
        } else {
            ElMessage.success("添加成功")
        }
    }
    cancelAddAttribute()
    isShowAddAttribute.value = false
    getAttributeList()
}

// 取消添加
const cancelAddAttribute = () => {
    isShowAddAttribute.value = false
    addAttributeForm.value = {
    attrName: '',
    attrValueList: [],
    categoryId: 0,
    categoryLevel: 0
}
}

// 切换添加属性时属性直的显示形式
const changeAttributeValueShow = (row: any, value: boolean, index:number) => {
    row.flag = value
    if(value && row.valueName.trim() === '') {
        ElMessage.error("属性值名称不能为空")
        row.flag = false
        addAttributeForm.value.attrValueList.splice(index,1)
    }
    console.log(addAttributeForm.value.attrValueList)
    if(addAttributeForm.value.attrValueList.find(item => {
        if(item !== row) {
            return item.valueName === row.valueName
        }
    })){
        addAttributeForm.value.attrValueList.splice(index,1)
        ElMessage.error("该属性值已经存在！")
        row.flag = false
    }

    // if(!row.flag)  {
    //     inputArr.value[index].focus()
    // }
}

// 聚焦效果
const handel = (el: any) => {
    if(el !== null) {
        el.focus()
    }
}

// 删除添加的属性值
const deleteAttributeValue = (row: any, index: number) => {
    addAttributeForm.value.attrValueList.splice(index,1)
    console.log(row);
    
}
// 初始化
onMounted(() => {
    getCategoryOne()
})
</script>
<template>
    <div class="attribute">
        <el-card>
            <el-form style="width: 100%;" :inline="true" class="demo-form-inline">

                <el-form-item label="一级分类">
                <el-select
                    placeholder="请选择"
                    clearable
                    style="width: 200px;"
                    label-width="100px"
                    v-model="categoryParmas.category1Id"
                    @change=" handleCategory1"
                    :disabled="isShowAddAttribute"
                >
                    <el-option v-for="item in categoryOneList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                </el-form-item>
                <el-form-item label="二级分类">
                <el-select
                    placeholder="请选择"
                    clearable
                    style="width: 200px;"
                    v-model="categoryParmas.category2Id"
                    @change="handleCategory2"
                    :disabled="isShowAddAttribute"
                >
                <el-option v-for="item in categoryTwoList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                </el-form-item>
                <el-form-item label="三级分类">
                <el-select
                    placeholder="请选择"
                    clearable
                    style="width: 200px;"
                    v-model="categoryParmas.category3Id"
                    @change="handleCategory3"
                    :disabled="isShowAddAttribute"
                >
                <el-option v-for="item in categoryThreeList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
                </el-form-item>
            </el-form>
        </el-card>
        <el-card v-if="!isShowAddAttribute">
            <template #header>
                <el-button @click="addAddAttribute " :disabled="!categoryParmas.category3Id" :icon="Plus" type="primary" size="">添加平台属性</el-button>
            </template>
            <el-table v-loading="tableLoading" :data="attributeList" border style="width: 100%">
                <el-table-column align="center" :width="80" type="index"  label="序号" />
                <el-table-column align="center" prop="attrName" label="属性名称"  />
                <el-table-column :width="500"  label="属性值名称">
                    <template v-slot="{ row }">
                        <el-tag v-for="item in row.attrValueList" :key="item.id" style="margin-right: 10px;">{{ item.valueName }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="操作" >
                    <template v-slot="{ row }">
                        <el-button type="primary" :icon="Edit" @click="addAddAttribute(row)">{{ row.name }}</el-button>
                        <el-button type=danger :icon="Delete" @click="deleteAttribute(row)"></el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <el-card v-else>
            <el-form :line="true" label-width="80px">
                <el-form-item label="属性名称" style="width: 300px;">
                    <el-input  v-model="addAttributeForm.attrName" placeholder="请输入属性名称"></el-input>
                </el-form-item>
            </el-form>
            <el-row style="padding-left: 10px;">
                <el-button @click="addAttributeValue" :disabled="!addAttributeForm.attrName" :icon="Plus" type="primary">添加属性值</el-button>
                <el-button >取消</el-button>
            </el-row>
            <el-table :data="addAttributeForm.attrValueList" style="margin-top: 20px; width: 100%; margin-left: 10px;" border >
                <el-table-column align="center" :width="80" type="index"  label="序号" />
                <el-table-column :width="500"  label="属性值名称">
                    <template v-slot="{ row, $index }">
                        <el-input :ref="handel" autofocus v-if="!row.flag" @blur="changeAttributeValueShow(row,true,$index)" v-model="row.valueName" placeholder="请输入属性值名称"></el-input>
                        <div @click="changeAttributeValueShow(row,false, $index)" v-else>{{ row.valueName }}</div>
                    </template>
                </el-table-column>
                <el-table-column prop="address" label="操作" >
                    <template v-slot="{ row, $index }">
                        <el-button circle @click="deleteAttributeValue(row,$index)" type=danger :icon="Delete"></el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-row style="margin-top: 20px;margin-left: 10px;">
                <el-button type="primary" :disabled="addAttributeForm.attrValueList.length === 0 || addAttributeForm.attrValueList.some(item => item.valueName.trim() === '')" @click="saveAttribute">保存</el-button>
                <el-button @click="cancelAddAttribute ">取消</el-button>
            </el-row>
        </el-card>
    </div>
</template>

<style scoped>
.attribute {
    .el-card {
        width: 100%;
        align-items: center;
        margin-bottom: 20px;
    }
}
</style>@/api/product/attribute@/types/product/attribute